package com.greedy.bulls.stock.user.controller.base;

import com.greedy.bulls.stock.common.exception.ComponentException;
import com.greedy.bulls.stock.common.exception.constants.ApplicationErrorCodeEnum;
import com.greedy.bulls.stock.common.utils.GlobalConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author: Yanxy
 * @Date: Created in:2023-08-05
 * Description: 基础工具模块-基础控制器
 */
@RestController
public class BaseController {

    /**
     * token存储接口
     */
    @Autowired
    private TokenStore tokenStore;

    /**
     * 获取当前请求的token
     *
     * @return token
     */
    protected String getCurrentToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 获取请求头中的令牌
        String token = request.getHeader("Authorization");
        if (null != token) {
            token = token.replace(OAuth2AccessToken.BEARER_TYPE, "").trim();
        }
        return token;
    }

    /**
     * 获取当前请求的用户ID
     *
     * @return 用户ID
     * @throws ComponentException 组件异常
     */
    protected Long getUserId() throws ComponentException {
        // 1.获取AccessToken信息
        OAuth2AccessToken token = tokenStore.readAccessToken(getCurrentToken());
        if (null == token) {
            throw new ComponentException(ApplicationErrorCodeEnum.SYS_NOT_VALID_TOKEN);
        }
        // 2.获取Token增强信息
        Map<String, Object> additionalInfos = token.getAdditionalInformation();
        if (null == additionalInfos) {
            throw new ComponentException(ApplicationErrorCodeEnum.SYS_NOT_ACCESS_USER);
        }
        // 3.获取用户ID
        Long userId = (Long) additionalInfos.get(GlobalConstants.OAUTH_DETAILS_USER_ID);
        if (null == userId) {
            throw new ComponentException(ApplicationErrorCodeEnum.SYS_NOT_ACCESS_USER);
        }
        return userId;
    }

}
